﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Services
{
    public class ServicesFactory
    {
        private static readonly ServicesFactory instance = new ServicesFactory();

        public static ServicesFactory Instance
        {
            get
            {
                return instance;
            }
        }

        private ServicesFactory()
        {

        }


        /// <summary>
        /// 根据接口,实例化对象
        /// </summary>
        /// <typeparam name="TService">接口</typeparam>
        /// <returns></returns>
        public TService GetService<TService>() where TService : class
        {
            string interfaceName = typeof(TService).FullName;

            var assembly = Assembly.GetExecutingAssembly();
            foreach (var item in assembly.GetTypes())
            {
                var instance = item.GetInterface(interfaceName);
                if (instance != null && instance.FullName == interfaceName)
                {
                    var obj = assembly.CreateInstance(item.FullName);
                    if (obj != null)
                    {
                        return obj as TService;
                    }
                }
            }

            throw new ArgumentNullException("没有找到实现" + interfaceName + "接口的类!");
        }

    }
}
